package com.yingsheng.bi.hks.web.component;

import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.util.ObjectUtils;

import java.util.Locale;

public class AbstractExceptionHandler implements ApplicationContextAware {

    protected final Logger log = LoggerFactory.getLogger(AbstractExceptionHandler.class);

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(@NotNull ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    protected String getExceptionMessage(String message) {
        Locale locale = LocaleContextHolder.getLocale();
        return getExceptionMessage(locale, message, null);
    }

    protected String getExceptionMessage(String message, Object[] args) {
        Locale locale = LocaleContextHolder.getLocale();
        return getExceptionMessage(locale, message, args);
    }

    protected String getExceptionMessage(Locale locale, String message, Object[] args) {
        String[] argMessages = getArgsMessage(locale, args);
        return applicationContext.getMessage(message, argMessages, message, locale);
    }

    protected String getArgsMessage(Object arg) {
        Locale locale = LocaleContextHolder.getLocale();
        return getArgsMessage(locale, arg);
    }

    protected String getArgsMessage(Locale locale, Object arg) {
        String[] argMessages = getArgsMessage(locale, new Object[]{arg});
        return ObjectUtils.isEmpty(argMessages)? null : argMessages[0];
    }

    protected String[] getArgsMessage(Object...args) {
        Locale locale = LocaleContextHolder.getLocale();
        return getArgsMessage(locale, args);
    }

    protected String[] getArgsMessage(Locale locale, Object...args) {
        if (!ObjectUtils.isEmpty(args)) {
            int length = args.length;
            String[] argMessages = new String[length];
            for (int i = 0; i < length; ++i) {
                if (args[i] != null) {
                    String msg = args[i].toString();
                    argMessages[i] = applicationContext.getMessage(msg, null, msg, locale);
                }
            }
            return argMessages;
        }
        return null;
    }
}
